package com.cl.ks.utils;

import com.querydsl.core.Tuple;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.dsl.*;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QueryDslUtil {

    public static List<Map<String, Object>> tupleListToMapList(List<Tuple> tuples, Expression[] fields) {
        List<Map<String, Object>> maps = new ArrayList<>();
        for (Tuple tuple : tuples) {
            maps.add(tupleToMap(tuple, fields));
        }
        return maps;
    }

    public static Map<String, Object> tupleToMap(Tuple tuple, Expression[] fields) {
        Map<String, Object> map = new HashMap<>();
        for (Expression field : fields) {
            String fieldStr = field.toString();
            if (fieldStr.contains(" as ")) {
                map.put(fieldStr.split(" as ")[1].trim(), tuple.get(field));
            } else {
                map.put(fieldStr.split("\\.")[1], tuple.get(field));
            }
        }
        return map;

    }

    public static BooleanExpression generatePowerExpression(EntityPathBase entityPath, StringPath stringPath, String userId, String roleId, String depId) {
        BooleanExpression booleanExpression = entityPath.isNotNull().and(entityPath.isNull());
        StringExpression power = Expressions.asString(",").concat(stringPath).concat(",");
        if (StringUtils.isNotBlank(userId) && !userId.equals("null")) {
            booleanExpression = booleanExpression.or(power.contains(",r_" + userId + ","));
        }
        if (StringUtils.isNotBlank(depId) && !depId.equals("null")) {
            booleanExpression = booleanExpression.or(power.contains(",b_" + depId + ","));
        }
        if (StringUtils.isNotBlank(roleId) && !roleId.equals("null")) {
            booleanExpression = booleanExpression.or(power.contains(",j_" + roleId + ","));
        }
        booleanExpression = booleanExpression.or(power.isNull()).or(power.isEmpty());
        return booleanExpression;
    }
}
